const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path");
const db = require("./db");
const dayjs = require("dayjs");
var duration = require("dayjs/plugin/duration"); // nodejs
dayjs.extend(duration);

let mainWindow;
app.commandLine.appendSwitch('disable-renderer-backgrounding')
app.commandLine.appendSwitch('disable-background-timer-throttling')

app.whenReady().then(() => {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 640,
    webPreferences: {
      preload: path.join(__dirname, "../preload.js"), // 关键路径配置[3](@ref)
      nodeIntegration: false, // 必须关闭
      contextIsolation: true, // 必须开启
    },
  });

  mainWindow.loadFile(path.join(__dirname, "../renderer/index.html"));
  // mainWindow.webContents.openDevTools();
});

// 数据库操作接口
ipcMain.handle("db-query", async (_, sql, params) => {
  try {
    console.log(sql);
    return await db.query(sql, params);
  } catch (error) {
    console.log(error);
  }
});

// renderTime
ipcMain.handle("refresh-time", async () => {
  try {
    const sql = `select type,sum(duration) as duration from records where start_time > "${dayjs()
      .startOf("d")
      .valueOf()}" and end_time < "${dayjs()
      .endOf("d")
      .valueOf()}" group by type`;
    console.log(sql);
    const res = await db.query(sql);
    let obj = {};
    res?.forEach((it) => {
      obj[it.type] = formatMilliseconds(it.duration);
      obj[`${it.type}Value`] = it.duration;
    });
    return obj;
  } catch (error) {
    console.log(error);
  }
});

function formatMilliseconds(ms) {
  // 创建 duration 对象（网页1的时间差概念延伸）
  const dur = dayjs.duration(ms);

  // 直接格式化输出（支持超过24小时的累计）
  return dur
    .format("HH[h]mm[m]ss[s]")
    .replace("h", "小时")
    .replace("m", "分")
    .replace("s", "秒");
}
